# -*- coding: cp1252 -*-
import threading,Queue
API_Key="59a5d7fa32f755407c332cb79e4ddbf4"
secret="f6820c1d8e4f0e6d6d69ea7ec4a01578"
api_url="http://ws.audioscrobbler.com/2.0/?api_key="+API_Key+"&method="
autocorrect="&autocorrect=1&"
from mutagen.mp3 import MP3
from mutagen.id3 import TPE1,TCON,TALB,APIC
from ant import Ant
import Levenshtein,urllib,urllib2,time
from lowlevel import *
from midlevel import *
class artisttor(Ant):
    switch=1
    def work(self,item):
        try:
            audio=MP3(item)
            artist=kickfeat(audio['TPE1'][0])
        except IOError,e:
            print "failure"
            return
        except KeyError,e:
            print "failure"
            return
        
        local_result=self.check_local(artist)
        if local_result=="delay":
            print local_result
            return
        elif local_result=="fail":
            print local_result
            return
        elif local_result=="work":
            pass
        else:
            print "local success"
            if(artisttor.switch==1):
                    audio.tags.add(TPE1(encoding=3,text=unicode(artisttor.local[su(artist.lower())],'utf-8')))
                    self.save_file(audio,item)
            return
        good_page=query("artist.getCorrection",l_artist=artist)
        if good_page=="not_in_database":
            self.fail_local_entry(su(artist.lower()))
            return
        elif good_page=="unknown":
            self.rem_local_entry(su(artist.lower()))
            return
        cor=getfield("name",good_page)
        if (cor!=""):
            if("&amp" in cor[0]):
                corri=cor[0][:cor[0].find("&")]+"&"+cor[0][cor[0].find("&")+5:]
            else:
                corri=cor[0]
            self.suc_local_entry(su(artist.lower()),su(corri))
            if Levenshtein.ratio(corri,su(artist.lower()))<1:
                print (corri+"  versus original "+artist.encode('utf-8')+" "+str(Levenshtein.ratio(corri,artist.encode('utf-8'))))
        else:
            if"<lfm status=\"ok\">" in good_page:
                self.suc_local_entry(su(artist.lower()),su(artist))
        if(artisttor.switch==1):
                audio.tags.add(TPE1(encoding=3,text=unicode(artisttor.local[su(artist.lower())],'utf-8')))
                self.save_file(audio,item)
        del audio
class genretor(Ant):
    switch=1
    def work(self,item):
        try:
            audio=MP3(item)
            artist=kickfeat(audio['TPE1'][0])
        except KeyError,e:
            print e
            return
        except IOError,e:
            print e
            return
        local_result=self.check_local(artist)
        if local_result=="delay":
            print local_result
            return
        elif local_result=="fail":
            print local_result
            return
        elif local_result=="work":
            pass
        else:
            print "local success"
            if(genretor.switch==1):
                    audio.tags.add(TCON(encoding=3,text=unicode(genretor.local[su(artist.lower())],'utf-8')))
                    self.save_file(audio,item)
            return
        good_page=query("artist.getTopTags",l_artist=artist)
        if good_page=="not_in_database":
            self.fail_local_entry(su(artist.lower()))
            return
        elif good_page=="unknown":
            self.rem_local_entry(su(artist.lower()))
            return
        cor=parse_genre(good_page)
        if (cor!=""):
            self.suc_local_entry(su(artist.lower()),su(cor))
        else:
            if"<lfm status=\"ok\">" in good_page:
                pass
        if(genretor.switch==1):
                audio.tags.add(TCON(encoding=3,text=unicode(genretor.local[su(artist.lower())],'utf-8')))
                self.save_file(audio,item)
        del audio
class albumtor(Ant):
    switch=1
    def work(self,item):
        try:
            audio=MP3(item)
            artist=kickfeat(audio['TPE1'][0])
            track=kickparentheses(audio['TIT2'][0])
        except IOError,e:
            print e
            return
        except KeyError,e:
            print e
            return
        
        good_page=query("track.getinfo",l_artist=artist,l_track=track)
        if good_page=="not_in_database" or good_page=="unknown":
            return
        cor=parse_album(good_page)
        try:
            album_tag=audio['TALB'][0]
        except:
            album_tag=cor[0]
        picture=cor[1]
        if album_tag=="no_album" or picture=="no_picture":
            try:
                temp=nachbrenner(artist,track)
                album_tag=temp[0]
                picture=temp[1]
            except:pass
        if(albumtor.switch==1):
            if album_tag!="no_album":
                audio.tags.add(TALB(encoding=3,text=unicode(su(album_tag),'utf-8')))
            if cor[1]!="no_picture":
                audio.tags.add(APIC(encoding=3,mime='image/'+cor[2],type=3,desc=u'Cover',data=picture))
            self.save_file(audio,item)
        del audio

